package com.psn.zjk.utils.nexus_uploader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;

import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;

import org.dom4j.DocumentException;
import org.xml.sax.SAXException;

import com.psn.zjk.utils.nexus_uploader.bean.Pom;
import com.psn.zjk.utils.nexus_uploader.utils.XMLUtils;

/** 查找要上传的jar
 * @Author: 张骏凯
 * @created 2019年3月21日 下午8:11:50 */
public final class JarUploader {

    public static List<Pom> findPoms(File path) throws JAXBException, SAXException, ParserConfigurationException,
            DocumentException, IOException {
        // 有效pom
        List<Pom> validPoms = new ArrayList<Pom>();
        if (path != null && path.exists() && path.isDirectory()) {
            File[] listFiles = path.listFiles();
            if (listFiles.length != 0) {
                // 所有pom文件
                List<Pom> poms = new ArrayList<Pom>();
                for (File file : listFiles) {
                    String name = file.getName();
                    if (name.endsWith(".pom")) {
                        FileInputStream stream = new FileInputStream(file);
                        String str = inputStreamToPom(stream);
                        Pom pomBean = XMLUtils.toJavaBean(str, Pom.class);
                        stream.close();
                        if (pomBean!=null&&!poms.contains(pomBean)) {
                            pomBean.setPom(file);
                            poms.add(pomBean);
                        }
                    } else if (name.endsWith(".jar") || name.endsWith(".war")) {
                        // 压缩包里的pom
                        Pom pomInJar = findPomInJar(file);
                        if (pomInJar!=null&&!poms.contains(pomInJar)) {
                            poms.add(pomInJar);
                        }
                    }
                }
                // 添加子文件夹的有效pom
                for (File file : listFiles) {
                    if (file.isDirectory()) {
                        List<Pom> childPoms = findPoms(file);
                        validPoms.addAll(childPoms);
                    }
                }
                // 获取当前文件夹内的有效pom
                for (Pom pomBean : poms) {
                    if (!pomBean.valid()) {
                        // 验证坐标有效性
                        continue;
                    }
                    // 打包方式
                    String packaging = pomBean.getPackaging();
                    String pre = pomBean.getArtifactId() + "-" + pomBean.getVersion();
                    String javadoc = pre + "-javadoc.jar";
                    String sources = pre + "-sources.jar";
                    if ("pom".equals(packaging)) {
                        // 单个pom文件
                        pomBean.setFile(pomBean.getPom());
                        validPoms.add(pomBean);
                        continue;
                    } else if ("war".equals(packaging) || "jar".equals(packaging)) {
                        // jar或者war包的名字
                        String fileName = pomBean.getFileName();
                        for (File file : listFiles) {
                            if (fileName.equals(file.getName())) {
                                // 编译包
                                pomBean.setFile(file);
                                validPoms.add(pomBean);
                                System.out.println("jar added:" + pomBean);
                            } else if (javadoc.equals(file.getName())) {
                                // 文档
                                pomBean.setJavadoc(file);
                            } else if (sources.equals(file.getName())) {
                                // 源码
                                pomBean.setSource(file);
                            }
                        }
                    }
                }
            }
        }
        return validPoms;
    }

    public static Pom findPomInJar(File jar) throws JAXBException, SAXException, ParserConfigurationException, DocumentException,
            IOException {
        JarInputStream stream = new JarInputStream(new FileInputStream(jar));
        while (true) {
            ZipEntry entry = stream.getNextEntry();
            if (entry == null) {
                stream.close();
                return null;
            }
            String name = entry.getName();
            if (name.endsWith("pom.xml")) {
                String pomXml = inputStreamToPom(stream);
                stream.close();
                Pom pom = XMLUtils.toJavaBean(pomXml, Pom.class);
                String absolutePath = jar.getAbsolutePath();
                int lastIndexOf = absolutePath.lastIndexOf(".");
                File file = new File(absolutePath.substring(0,lastIndexOf) + ".pom");
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                FileWriter fw = new FileWriter(file);
                fw.write(pomXml);
                fw.flush();
                fw.close();
                pom.setPom(file);
                return pom;
            }
        }

    }

    public static void upload(String path, String url, String repositoryId) throws DocumentException, JAXBException,
            SAXException, ParserConfigurationException, IOException {
        List<Pom> poms = findPoms(new File(path));
        if (poms.size() == 0) {
            System.out.println("未找到可以上传的文件");
            return;
        }
        StringBuffer buffer = new StringBuffer();
        for (Pom pom : poms) {
            buffer.append("call mvn deploy:deploy-file");
            buffer.append(" -DgroupId=");
            buffer.append(pom.getGroupId());
            buffer.append(" -DartifactId=");
            buffer.append(pom.getArtifactId());
            buffer.append(" -Dversion=");
            buffer.append(pom.getVersion());
            buffer.append(" -Dfile=");
            buffer.append(pom.getFile().getAbsolutePath());
            buffer.append(" -Durl=");
            buffer.append(url);
            buffer.append(" -Dpackaging=");
            buffer.append(pom.getPackaging());
            buffer.append(" -DrepositoryId=");
            buffer.append(repositoryId);
            File source = pom.getSource();
            File javadoc = pom.getJavadoc();
            File pomFile = pom.getPom();
            if (source != null) {
                buffer.append(" -Dsources=").append(source);
            }
            if (javadoc != null) {
                buffer.append(" -Djavadoc=").append(javadoc);
            }
            if (pomFile != null) {
                buffer.append(" -DpomFile=").append(pomFile);
            }
            buffer.append(System.getProperty("line.separator"));
        }
        buffer.append("pause");
        File file = new File("delpoyToNexus.bat");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.write(buffer.toString());
        fileWriter.flush();
        fileWriter.close();
        String separator = System.getProperty("line.separator");
        System.out.println("===============" + separator + "bat file crreated at:" + file.getAbsolutePath() + separator
                + "==========");
    }

    private static String inputStreamToPom(InputStream stream) throws IOException, JAXBException, SAXException,
            ParserConfigurationException {
        String str = null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuffer buffer = new StringBuffer();
        while ((str = reader.readLine()) != null) {
            buffer.append(str).append(System.getProperty("line.separator"));
        }
        return buffer.toString();

    }
}
